from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.models.user_role import UserRole as UserRoleModel, UserRoleInDB
from app.schemas.user_role import UserRole as UserRoleSchema, UserRoleCreate, UserRoleUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/user-roles", tags=["用户角色管理"])

@router.post("/create", response_model=APIResponse[UserRoleSchema])
def create_user_role(user_role: UserRoleCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating user role with user_id: {user_role.user_id}, role_id: {user_role.role_id}")
    
    # 检查用户角色关联是否已存在
    db_user_role = db.query(UserRoleModel).filter(
        UserRoleModel.user_id == user_role.user_id,
        UserRoleModel.role_id == user_role.role_id
    ).first()
    if db_user_role:
        logger.warning(f"User role already registered with user_id: {user_role.user_id}, role_id: {user_role.role_id}")
        return error_response(message="User role already registered", code=400)
    
    # 创建新用户角色关联
    db_user_role = UserRoleModel(
        user_id=user_role.user_id,
        role_id=user_role.role_id,
        create_time=datetime.utcnow()
    )
    
    db.add(db_user_role)
    db.commit()
    db.refresh(db_user_role)
    
    # 转换为Pydantic模型
    user_role_response = UserRoleInDB.model_validate(db_user_role)
    
    logger.info(f"User role created successfully with ID: {db_user_role.id}")
    return success_response(data=user_role_response, message="User role created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[UserRoleSchema]])
def read_user_roles(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching user roles with skip: {skip}, limit: {limit}")
    
    user_roles = db.query(UserRoleModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    user_roles_response = [UserRoleInDB.model_validate(user_role) for user_role in user_roles]
    total = db.query(UserRoleModel).count()
    
    logger.info(f"Found {len(user_roles)} user roles")
    return paginated_response(
        items=user_roles_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{user_role_id}", response_model=APIResponse[UserRoleSchema])
def read_user_role(user_role_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching user role with ID: {user_role_id}")
    
    db_user_role = db.query(UserRoleModel).filter(UserRoleModel.id == user_role_id).first()
    if db_user_role is None:
        logger.warning(f"User role not found with ID: {user_role_id}")
        return error_response(message="User role not found", code=404)
    
    # 转换为Pydantic模型
    user_role_response = UserRoleInDB.model_validate(db_user_role)
    
    logger.info(f"User role found with ID: {user_role_id}")
    return success_response(data=user_role_response)

@router.put("/{user_role_id}", response_model=APIResponse[UserRoleSchema])
def update_user_role(user_role_id: int, user_role: UserRoleUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating user role with ID: {user_role_id}")
    
    db_user_role = db.query(UserRoleModel).filter(UserRoleModel.id == user_role_id).first()
    if db_user_role is None:
        logger.warning(f"User role not found with ID: {user_role_id}")
        return error_response(message="User role not found", code=404)
    
    # 更新用户角色关联信息
    update_data = user_role.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_user_role, key, value)
    
    db.commit()
    db.refresh(db_user_role)
    
    # 转换为Pydantic模型
    user_role_response = UserRoleInDB.model_validate(db_user_role)
    
    logger.info(f"User role updated successfully with ID: {user_role_id}")
    return success_response(data=user_role_response, message="User role updated successfully")

@router.delete("/{user_role_id}", response_model=APIResponse[None])
def delete_user_role(user_role_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting user role with ID: {user_role_id}")
    
    db_user_role = db.query(UserRoleModel).filter(UserRoleModel.id == user_role_id).first()
    if db_user_role is None:
        logger.warning(f"User role not found with ID: {user_role_id}")
        return error_response(message="User role not found", code=404)
    
    db.delete(db_user_role)
    db.commit()
    
    logger.info(f"User role deleted successfully with ID: {user_role_id}")
    return success_response(message="User role deleted successfully")
